import { compile, resolveTsConfig } from './tsUtil';
import child_process from 'node:child_process';
import { getProcessArg } from './parameter';
import { clearCompiledFile } from './clear';

export function compileSource() {
  //读取配置
  let tsConfig = resolveTsConfig('./tsconfig.json');
  //编译
  compile(tsConfig.fileNames, tsConfig.options);
}

export async function publish(tag: string) {
  await new Promise<void>((resolve, reject) => {

    const nwProcess = child_process.spawn(
        'npm',
        ['publish', '--tag', tag, '--registry=https://registry.npmjs.org/'],
        {
          stdio: 'inherit',
        },
    );
    nwProcess.on('close', () => {
      console.log(`执行事件 close`);
      process.nextTick(function () {
        process.exit(0);
      });
      resolve();
    });
    nwProcess.on('error', (error) => {
      console.log(`执行事件 error: ${error}`);
      reject(error);
    });

  });
}

function main() {
  //清空编译内容
  clearCompiledFile();
  //编译
  compileSource();
  //获取发布标签
  let tag = getProcessArg('tag');
  //发布
  publish(tag).then(() => {
    //清空编译内容
    clearCompiledFile();
  });
}

main();

